import Taro from '@tarojs/taro'

let cachedDebugFlag: boolean | undefined

function readDebugFlag(): boolean {
  if (cachedDebugFlag !== undefined) return cachedDebugFlag
  try {
    const value = Taro.getStorageSync('DEBUG_FRONTEND_ANALYSIS')
    if (value === true || value === 1 || value === '1') {
      cachedDebugFlag = true
    } else if (typeof value === 'string' && value.toLowerCase() === 'true') {
      cachedDebugFlag = true
    } else {
      cachedDebugFlag = false
    }
  } catch {
    cachedDebugFlag = false
  }
  return cachedDebugFlag
}

export function setFrontendDebug(enabled: boolean): void {
  try {
    Taro.setStorageSync('DEBUG_FRONTEND_ANALYSIS', enabled ? '1' : '0')
  } catch {}
  cachedDebugFlag = enabled
}

export function installLogFilter(): void {
  const debugEnabled = readDebugFlag()
  const original = {
    log: console.log.bind(console),
    info: console.info.bind(console),
    debug: console.debug ? console.debug.bind(console) : console.log.bind(console),
    warn: console.warn.bind(console),
    error: console.error.bind(console)
  }

  console.log = (...args: any[]) => {
    if (debugEnabled) original.log(...args)
  }
  console.info = (...args: any[]) => {
    if (debugEnabled) original.info(...args)
  }
  console.debug = (...args: any[]) => {
    if (debugEnabled) original.debug(...args)
  }
  // 警告和错误始终打印
  console.warn = (...args: any[]) => {
    original.warn(...args)
  }
  console.error = (...args: any[]) => {
    original.error(...args)
  }
}

// 便于在页面中直接获取当前状态
export function isFrontendDebug(): boolean {
  return readDebugFlag()
}


